﻿import VTitle from '@/components/common/MainTitle.vue'
import EditParameters from '@/components/Events/EditParameters.vue'
import EditResponse from '@/components/Events/EditResponse.vue'
// 导入动态表单事件的组件
import ImportMethod from '@/components/common/TheImportMethod.vue'
// 导出动态表单事件的组件
import ExportMethod from '@/components/common/TheExportMethod.vue'
export default {
  components: { VTitle, EditParameters, EditResponse, ImportMethod, ExportMethod },
  data () {
    return {
      titleName: '表单页面事件定义',
      operationType: '',
      // 检索部分
      searchKey: '',
      isSearch: false,
      filterData: [],
      // 表格部分
      ruleForm: {
        tableData: []
      },
      rules: {
        no: [
          { required: true, message: '事件编号不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '事件名称不能为空', trigger: 'blur' },
          { pattern: /^[\u4e00-\u9fa5][\u4e00-\u9fa5_a-zA-Z0-9\-]*$/, message: '事件名称建议使用中文字符', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '事件分类不能为空', trigger: 'change' }
        ]
      },
      // 点击某一条数据时，弹框的部分
      editInfo: {
        request_parameters: '',
        response_data: '',
        status: 'show'
      },
      currentShowDialog: '',
      editRow: '',
      totalData: [],
      // 页码部分
      totalLength: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,
      // 导入页面相关
      importPageInfo: {
        title: '导入动态表单事件的脚本',
        apiRouter: '/events4dform/script/import',
        dialog: false
      },
      // 导出相关的操作
      exportPageInfo: {
        title: '导出动态表单事件的脚本',
        apiRouter: '/events4dform/script/export',
        type: 'dynamicEvents',
        dialog: false
      }
    }
  },
  created () {
    this.getAllEvents()
  },
  methods: { 
    // 获取所有的自定义事件资料
    getAllEvents () {
      this.operationType = ''
      this.loading = true
      this.$get('/events4dform').then(data => {
        let dataInfo = data.data.result
        if (dataInfo.code === 'failed') {
          this.$message({
            message: dataInfo.msg,
            type: 'warning'
          })
        }
        if (dataInfo.code === 'success') {
          this.totalData = dataInfo.data
          this.totalLength = dataInfo.data.length
          // 调用方法进行页面渲染
          this.showData(this.totalData)
        }
        this.loading = false
      }).catch(error => {
        console.log(error)
      })
    },
    // 定义表头的信息
    handelHelpKey (h, {column}) {
      if (column.labelClassName) {
        return (
          <el-tooltip effect="dark" placement="top">
            <div slot='content'>{column.labelClassName}</div>
            <span><span style="color:red">*</span>{column.label}</span>
          </el-tooltip>
        )
      } else {
        return (
          h('span', [
            h('span', {style: {color: 'red'}}, ['*']),
            h('span', [column.label])
          ])
        )
      }
    },
    // 编辑事件参数设定时
    editTableCloumn (row, index, currentShow) {
      this.currentShowDialog = currentShow
      this.editRow = index
      this.editInfo.request_parameters = row.request_parameters
      this.editInfo.response_data = row.response_data
      this.editInfo.status = 'edit'
    },
    // 查看事件参数设定时
    showTableCloumn (row, index, currentShow) {
      this.currentShowDialog = currentShow
      this.editRow = index
      this.editInfo.request_parameters = row.request_parameters
      this.editInfo.response_data = row.response_data
      this.editInfo.status = 'show'
    },
    // 编辑事件参数设定时成功返回的数据
    sureEdit (editContent) {
      if (this.currentShowDialog === 'params') {
        this.currentShowDialog = ''
        this.ruleForm.tableData[this.editRow].request_parameters = editContent
      } else if (this.currentShowDialog === 'response') {
        this.currentShowDialog = ''
        this.ruleForm.tableData[this.editRow].response_data = editContent
      }  
    },
    // 删除单条数据时
    handleSingleDelete (row, index) {
      // 当为新增时移除新增项时
      if (this.operationType === 'add') {
        this.ruleForm.tableData.splice(index, 1)
      } else {
        this.submitDelete(row.no)
      }
    },
    // 提交删除的方法
    submitDelete (eventId) {
      this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonClass: 'el-button--info',
        cancelButtonText: '取消'
      }).then(() => {
        this.loading = true
        this.$delete('/events4dform/' + eventId).then(data => {
          this.loading = false
          if (data.status === 204) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          }
          this.getAllEvents()
        }).catch(error => {
          console.log(error)
        })
      }).catch(() => {})
    },
    // 向表中新增一条数据
    addData () {
      this.operationType = 'add'
      this.ruleForm.tableData.unshift({
        no: '',
        name: '',
        category: 'Customerize',
        desc: '',
        request_parameters: '',
        response_data: '',
        newData: 'newData'
      })
    },
    // 提交新增的方法
    submitAdd () {
      if (this.ruleForm.tableData.length) {
        let newArry = []
        this.ruleForm.tableData.forEach(val => {
          // 在表格中所有的数据中，找到新增的数据
          if (val.newData === 'newData') {
            // 将新增数据中的 newData 属性和值去掉并保存到新的数组中
            let objExam = {}
            for (let key in val) {
              if (key !== 'newData') {
                objExam[key] = val[key]
              }
            }
            newArry.push(objExam)
          }
        })
        if (newArry.length) {
          this.loading = true
          this.$post('/events4dform', {
            data: newArry
          }).then(data => {
            this.loading = false
            if (data.data.result.code === 'success') {
              this.$message({
                message: '自定义事件添加成功！',
                type: 'success'
              })
              this.getAllEvents()
            } else if (data.data.result.code === 'failed') {
              this.$message({
                message: data.data.result.msg,
                type: 'error'
              })
            }
          }).catch(error => {
            console.log(error)
          })
        } else {
          this.$message({
            message: '还没有新增的自定义事件资料，不需要提交',
            type: 'warning'
          })
        }
      } else {
        this.$message({
          message: '还没有自定义事件资料，不需要提交',
          type: 'warning'
        })
      }
    },
    // 点击左下方编辑按钮时
    editData () {
      if (this.ruleForm.tableData.length) {
        this.operationType = 'edit'
      } else {
        this.$message({
          message: '还没有自定义事件资料，无法进行编辑操作',
          type: 'warning'
        })
      }
    },
    // 提交编辑的方法
    submitEdit () {
      this.loading = true
      this.$patch('/events4dform', {
        data: this.totalData
      }).then(data => {
        this.loading = false
        if (data.data.result.code === 'success') {
          this.$message({
            message: '编辑数据成功',
            type: 'success'
          })
          this.getAllEvents()
        } else if (data.data.result.code === 'failed') {
          this.$message({
            message: data.data.result.msg,
            type: 'error'
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 点击确定提交的按钮时
    submitForm (forms, submitType) {
      this.$refs[forms].validate((valid) => {
        if (valid) {
          if (submitType === 'edit') {
            this.submitEdit()
          } else if (submitType === 'add') {
            this.submitAdd()
          }
        } else {
          return false
        }
      })
    },
    // 点击取消按钮时
    resetForm (forms) {
      this.$refs[forms].clearValidate()
      this.operationType = ''
      this.getAllEvents()
    },
    // 将页码与数据关联
    showData (myData) {
      // 渲染表格的数据存放在 this.tableData 中
      this.ruleForm.tableData = []
      if (myData.length) {
        let from = (this.currentPage - 1) * this.pageSize
        let to = this.currentPage * this.pageSize
        if (to > myData.length) {
          to = myData.length
        }
        for (; from < to; from++) {
          this.ruleForm.tableData.push(myData[from])
        }
      }
    },
    // 底部页码的部分
    handleSizeChange (val) {
      this.pageSize = val
      // 需要判断是否是检索的数据
      if (this.isSearch) {
        this.showData(this.filterData)
      } else {
        this.showData(this.totalData)
      }
    },
    handleCurrentChange (val) {
      this.currentPage = val
      // 需要判断是否是检索的数据
      if (this.isSearch) {
        this.showData(this.filterData)
      } else {
        this.showData(this.totalData)
      }
    },
    // 导入事件成功时
    finishedImportOperation () {
      this.importPageInfo.dialog = false
      this.$message({
        message: '导入动态表单事件的脚本成功',
        type: 'success'
      })
      this.getAllEvents()
    }
  },
  watch: {
    // 搜索的功能
    searchKey: {
      handler: function (val, oldVal) {
        // 当检索的内容为空时需要将表格的内容还原
        if (this.$trim(val) === '') {
          this.pageSize = 10
          this.currentPage = 1
          this.totalLength = this.totalData.length
          this.isSearch = false
          // 调用方法进行页面渲染
          this.showData(this.totalData)
        } else {
          // 检索结果的数据存放在 this.filterData 中
          this.filterData = []
          this.totalData.forEach((value, index) => {
            if (value.no.indexOf(this.searchKey) >= 0 || value.name.indexOf(this.searchKey) >= 0) {
                this.filterData.push(value)
              }
          })
          this.isSearch = true
          this.currentPage = 1
          this.totalLength = this.filterData.length
          // 调用方法进行页面渲染
          this.showData(this.filterData)
        }
      },
      deep: true
    }
  }
}
